<?php
namespace app\api\model;
use think\Db;
use think\Model;
/*聊天信息模型*/
class ChatMsg extends CommonModel
{
    protected $table_name = 'chat_msg_user';
    public function __construct($args = [])
    {
        parent::__construct($args);
    }

    /** 获取10条消息记录
     * @param $fuser 请求历史记录的加密的client_id
     * @param $tuser 对方对话的加密的client_id
     * @param $fist_msgid 基于这则消息的前列5条消息
     * @return int
     */
    public function getlog($fuser,$tuser,$fist_msgid = null)
    {
        //设置信息已查看
        db('chat_msg_user')->where(['tuser'=>$fuser,'tu_skim'=>0])->update(['tu_skim'=>1]);
        $where = empty($fist_msgid) ? "" : " c.id < ".intval($fist_msgid)." and ";
        $sql = "
            SELECT mu.*,c.content,c.add_time,c.content_type from ecs_chat_msg_user AS mu
            LEFT JOIN ecs_chat_msg AS c ON mu.msg_id = c.id
            WHERE $where ((mu.fuser = ? and mu.tuser = ?) or (mu.fuser = ? and mu.tuser = ?))
            ORDER BY c.id DESC
            LIMIT 5
        ";

        $data =   Db::query($sql,[$fuser,$tuser,$tuser,$fuser]);
        if(!empty($data))
            foreach($data as $k=>$v)
            {
                if($v['content_type'] == 'photo' && strpos($v['content'],"https://") === false && strpos($v['content'],"http://") === false)
                {
                    $data[$k]['content'] = $this->getDomain().'/'.$v['content'];
                }
                $data[$k]['time'] = $data[$k]['add_time'] = date('Y-m-d H:i:s',$v['add_time']);

            }
        return $data;


    }


    public function getDomain()
    {
        $configModel = new Config();
        $config = $configModel->info(['cKey'=>'domain']);
        return !empty($config) ? $config['cValue'] : "";
    }


    public function getLogUser($client_id)
    {
        $log = db('chat_msg_user')->field('fuser,tuser')
            ->where('fuser|tuser','=',$client_id)
            ->order("id DESC")
            ->select();
        $userArr = [];
        foreach($log as $v)
        {
            if($v['fuser'] != $client_id)
                $userArr[] = $v['fuser'];
            if($v['tuser'] != $client_id)
                $userArr[] = $v['tuser'];
        }
        $userArr = array_unique($userArr);

        if(empty($userArr)) return [];

        foreach($userArr as $k=>$v)
        {
            $userArr[$k] = "'".$v."'";
        }
        //获取客户端id，匿名，以及当前用户与最近聊天的用户的相关没查阅的信息数量
        $sql = "
                select u.enc_client_id,u.nickname,u.kf_id,k.nickname as kf_nickname,
                  (select count(*) from ecs_chat_msg_user where tu_skim = 0 and tuser = '$client_id' and fuser = u.enc_client_id ) as no_skim
                  from ecs_user as u
                  LEFT JOIN ecs_kf as k ON k.kf_id = u.kf_id
                  where u.enc_client_id in (".implode($userArr,',').")
                  ORDER BY  no_skim DESC,FIND_IN_SET(u.enc_client_id,'".str_replace("'","",implode($userArr,','))."') LIMIT 8";

        $data = Db::query($sql);
        if(!empty($data))
        {
            foreach($data as $k=>$v)
            {
                //nickname，如果是客服，则用客服匿名，如果nickname为空，则默认为'匿名'
                $data[$k]['nickname'] = empty($v['kf_nickname']) ? $v['nickname'] : (empty($v['nickname']) ? "匿名" : $v['nickname']);
            }
        }
        return $data;
    }

    //根据一个客户端，获取未浏览的数量
    public function getOneNoSkimLog($fuser,$tuser)
    {
        $sql = "select count(*) as no_skim from ecs_chat_msg_user where tu_skim = 0 and tuser = '$tuser' and fuser = '$fuser' ";
        $data = Db::query($sql);
        return !empty($data) ? $data[0]['no_skim'] : 0;
    }

    //获取用户与客服聊天的所有clientid
    public function getUserConnectKfClientId($client_id)
    {
        $where = [
            'fuser|tuser' => $client_id
        ];
        $result= db($this->table_name)->field('fuser,tuser')->where($where)->select();

        $kfClient_id = [];

        if(!empty($result))
        {
            foreach($result as $v)
            {
                if(!in_array($v['fuser'],$kfClient_id) && !in_array($v['tuser'],$kfClient_id) )
                {
                    $kfClient_id[] = $v['fuser'] == $client_id ? $v['tuser'] : $v['fuser'];
                }
            }
            $kfClient_id = array_unique($kfClient_id);
        }

        return $kfClient_id;

    }
}